<!-- src/components/recommendation/AIRecommendation.vue -->
<template>
  <div>
    <!-- 输入表单对话框 -->
    <el-dialog v-model="dialogVisible" title="AI旅行建议" width="600px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="出行人数" prop="numPeople">
          <el-input-number v-model="form.numPeople" :min="1" />
        </el-form-item>

        <el-form-item label="平均年龄" prop="avgAge">
          <el-input-number v-model="form.avgAge" :min="1" :max="100" />
        </el-form-item>

        <el-form-item label="目的地" prop="destination">
          <el-input v-model="form.destination" placeholder="请输入目的地" />
        </el-form-item>

        <el-form-item label="出行天数" prop="days">
          <el-input-number v-model="form.days" :min="1" :max="30" />
        </el-form-item>

        <!-- 修改出行风格为输入框 -->
        <el-form-item label="出行风格" prop="travelStyle">
          <el-input v-model="form.travelStyle" placeholder="请输入出行风格，例如：休闲度假、文化探索" />
        </el-form-item>

        <!-- 修改预算范围为输入框 -->
        <el-form-item label="预算范围" prop="budget">
          <el-input v-model="form.budget" placeholder="请输入预算范围，例如：3000元/人" />
        </el-form-item>

        <!-- 修改偏好标签为输入框 -->
        <el-form-item label="偏好标签" prop="preferences">
          <el-input v-model="preferencesInput" placeholder="请输入偏好，多个偏好用逗号分隔，例如：历史古迹,自然景观"
            @input="handlePreferencesInput" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          生成建议
        </el-button>
      </template>
    </el-dialog>

    <!-- 全屏加载 -->
    <el-loading v-model="fullscreenLoading" fullscreen text="正在生成AI旅行建议..." />
    <!-- 结果展示对话框 -->
    <el-dialog v-model="resultDialogVisible" title="AI旅行建议" width="600px" :close-on-click-modal="false">
      <div class="result-content">
        <div class="section">
          <h3>总体建议</h3>
          <p>{{ result.summary }}</p>
        </div>
        <div class="section">
          <h3>出行小贴士</h3>
          <p>{{ result.travelTips }}</p>
        </div>
        <div class="section">
          <h3>预算分析</h3>
          <p>{{ result.budgetAnalysis }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { travelRecommendByGpt } from '@/api/Gpt'
import { useFormStore } from '@/stores/FormStore'
import { getAttractionInfo } from '@/api/Attraction'

// 添加偏好输入处理
const preferencesInput = ref('')
// 处理偏好输入
const handlePreferencesInput = (value: string) => {
  form.preferences = value.split(',').map(p => p.trim()).filter(p => p)
}
const importLoading = ref(false)

const dialogVisible = ref(false)
const resultDialogVisible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()
const fullscreenLoading = ref(false)
const formStore = useFormStore()

const sleep = (ms: number): Promise<void> => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
  })
}

const form = reactive({
  numPeople: 1,
  avgAge: 25,
  destination: '',
  days: 1,
  travelStyle: '',
  budget: '',
  preferences: [] as string[]
})

const result = reactive({
  summary: '',
  travelTips: '',
  budgetAnalysis: ''
})

const rules = {
  numPeople: [{ required: false, message: '请输入出行人数' }],
  avgAge: [{ required: false, message: '请输入平均年龄' }],
  destination: [{ required: true, message: '请输入目的地' }],
  days: [{ required: false, message: '请输入出行天数' }],
  travelStyle: [{ required: false, message: '请输入出行风格' }],
  budget: [{ required: false, message: '请输入预算范围' }],
  preferences: [{ required: false, message: '请输入偏好标签' }]
}





// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    fullscreenLoading.value = true
    loading.value = true

    // 保存表单数据
    formStore.setFormData({
      numPeople: form.numPeople,
      avgAge: form.avgAge, 
      destination: form.destination,
      days: form.days,
      travelStyle: form.travelStyle,
      budget: form.budget,
      preferences: form.preferences
    })

    const requestData = {
      ...form,
      preferences: Array.isArray(form.preferences) ? form.preferences.join(',') : form.preferences
    }
    const response = await travelRecommendByGpt(requestData)

    if (response.status === 'success') {
      // 展示整体建议
      result.summary = response.data.analysis.summary
      result.travelTips = response.data.analysis.travel_tips
      result.budgetAnalysis = response.data.analysis.budget_analysis

      // 获取AI推荐的景点列表(原有功能)
      let recommendedSpots = [...response.data.recommended_spots];
      
      // 预设的景点ID - 这些将被自动导入到规划栏
      const fixedSpotIds = [4798, 4796, 4801, 4811];
      const autoImportSpots = [];
      
      try {
        // 获取预设景点信息
        for (const id of fixedSpotIds) {
          const attractionResponse = await getAttractionInfo(id);
          if (attractionResponse && attractionResponse.data) {
            // 格式化景点数据
            const spotData = {
              attractionId: attractionResponse.data.attractionId,
              regionId: attractionResponse.data.regionId,
              name: attractionResponse.data.name,
              description: attractionResponse.data.description,
              address: attractionResponse.data.address,
              image: attractionResponse.data.image,
              latitude: attractionResponse.data.latitude,
              longitude: attractionResponse.data.longitude,
              priceRange: attractionResponse.data.priceRange,
              openingHours: attractionResponse.data.openingHours,
              likeCount: attractionResponse.data.likeCount,
              commentCount: attractionResponse.data.commentCount,
              attractionRating: attractionResponse.data.attractionRating,
              recommendedVisitTime: attractionResponse.data.recommendedVisitTime,
              recommendedVisitSeason: attractionResponse.data.recommendedVisitSeason,
              selectCount: attractionResponse.data.selectCount,
              duration: attractionResponse.data.recommendedVisitTime ? 
                parseInt(attractionResponse.data.recommendedVisitTime) : 120,
              aiSuggestion: '系统推荐景点'
            };
            
            // 添加到自动导入列表
            autoImportSpots.push(spotData);
            
          }
        }
        
        // 发送自动导入事件 - 这是新增的事件
        emit('auto-import-spots', autoImportSpots);
        
      } catch (error) {
        console.error('获取预设景点失败:', error);
        // 即使获取预设景点失败，也继续处理其他景点
      }

      // 发送推荐景点列表(原有功能)
      emit('spots-recommended', recommendedSpots);

      dialogVisible.value = false;
      resultDialogVisible.value = true;
    } else {
      ElMessage.error(response.message);
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + error.message);
  } finally {
    fullscreenLoading.value = false;
    loading.value = false;
  }
}

const prefillForm = () => {
  const lastData = formStore.lastFormData
  if (lastData) {
    form.numPeople = lastData.numPeople
    form.avgAge = lastData.avgAge
    form.destination = lastData.destination
    form.days = lastData.days
    form.travelStyle = lastData.travelStyle
    form.budget = lastData.budget
    form.preferences = lastData.preferences
    preferencesInput.value = lastData.preferences.join(', ')
  }
}

watch(() => dialogVisible.value, (newVal) => {
  if (newVal) {
    prefillForm()
  }
})

defineExpose({
  dialogVisible,
  prefillForm
})

const emit = defineEmits(['spots-recommended', 'auto-import-spots'])
</script>

<style scoped>
.result-content {
  max-height: 60vh;
  overflow-y: auto;
}

.section {
  margin-bottom: 20px;
}

.section h3 {
  margin: 0 0 10px;
  color: #333;
}

.section p {
  margin: 0;
  line-height: 1.6;
  color: #666;
}

.result-content {
  max-height: 60vh;
  overflow-y: auto;
}

.section {
  margin-bottom: 20px;
}

.section h3 {
  margin: 0 0 10px;
  color: #333;
}

.section p {
  margin: 0;
  line-height: 1.6;
  color: #666;
}

.note-section {
  margin-top: 20px;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  border-left: 3px solid #67c23a;
}

.note-text {
  color: #67c23a;
  font-size: 14px;
}

</style>